package com.cys.markdown.doc.admin.config;

import com.cys.markdown.doc.admin.shiro.ExtAuthenticationFilter;
import com.cys.markdown.doc.admin.shiro.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro 配置文件类
 * Created by caiyushen on 2018/05/22.
 */
@Configuration
public class ShiroConfig {

    @Value("${shiro.flag}")
    private Boolean shiroFlag;

    /**
     * Shiro 拦截器
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //配置shiro默认登录界面地址，前后端分离中登录界面跳转应由前端路由控制，后台仅返回json数据
        shiroFilterFactoryBean.setLoginUrl("/login/toSessionTimeout");
//        shiroFilterFactoryBean.setLoginUrl("/login/toIndex");
        // 登录成功后要跳转的链接
//        shiroFilterFactoryBean.setSuccessUrl("/admin/main/toIndex");
        shiroFilterFactoryBean.setSuccessUrl("/login/toAuthorized");
        //未授权界面;
//        shiroFilterFactoryBean.setUnauthorizedUrl("/login/toIndex");
        shiroFilterFactoryBean.setUnauthorizedUrl("/login/toSessionTimeout");

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //注意过滤器配置顺序 不能颠倒
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了，登出后跳转配置的loginUrl
        filterChainDefinitionMap.put("/logout", "logout");
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/static/**", "anon");
        // 登录的Controller
        filterChainDefinitionMap.put("/login/**", "anon");
        if (shiroFlag) {
            filterChainDefinitionMap.put("/**", "authc");  //后台权限
        }
        //Shiro连接约束配置,即过滤链的定义
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        if (shiroFlag) {
            /*===Shiro 自定义拦截器 start===*/
            Map<String, Filter> filters = new HashMap<>();
            //shiro自定义拦截器 不要通过Bean 注入set进去，不然Spring bean识别会乱了权限校验
            //拦截需要登录才能访问的资源
            filters.put("authc", new ExtAuthenticationFilter());
            ///退出过滤器
//        filters.put("logout", logoutFilter());

            shiroFilterFactoryBean.setFilters(filters);
            /*===Shiro 自定义拦截器 end===*/
        }
        return shiroFilterFactoryBean;
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * ）
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);//散列的次数，比如散列两次，相当于 md5(md5(""));
        return hashedCredentialsMatcher;
    }

    /**
     * 注册一个自定义shiroRealm的Bean
     *
     * @Bean 在Spring容器里面注册一个Bean
     */
    @Bean("shiroRealm")
    public ShiroRealm shiroRealm() {
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setAuthorizationCacheName("authorization");
        return shiroRealm;
    }


    /**
     * 注册一个securityManager的Bean
     *
     * @Bean 在Spring容器里面注册一个Bean
     * shiroRealm 上面注册的自定义bean
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm());
        return securityManager;
    }

    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     *
     * @param securityManager 上面注册的Bean
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}